package com.mapbased.wfw.components;

import java.io.*;
import java.util.*;

import org.dom4j.*;
import com.mapbased.wfw.*;
import javax.servlet.*;

/**
 * <p>Title: </p>
 *
 * <p>Description:Include another page while render </p>
 *save memory than using template
 * <p>Copyright: Copyright (c) 2004</p>
 *
 * <p>Company: mapbased.com</p>
 *
 * @author chy_hs(Baily)
 * @version 1.0
 */
public class Include
    extends Component
{

    public Include()
    {
        super();
    }

    Page pageRef;
    String jsp;

    /**
     * a component can choose to parse an element or not.
     *
     * @param ele Element
     * @param loader PageLoader
     * @return Element or null:if wanna page loader parse the
     *   component,return the ele, else return null
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public Element parseXml(Element ele,PageLoader.LoadContext
                            lc)
    {

        String page=ele.attributeValue("page");
        if(page.endsWith(".jsp"))
        {
            jsp=page;
        }
        else
        {

            pageRef = lc.loader.getPage(page, this.locale);
        }

        return null;
    }

    /**
     * render
     *
     * @param context RenderContext
     * @throws IOException
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public void render(RenderContext context)
        throws IOException
    {
        if (this.pageRef == null) {
            try {
                context.getRequest().getRequestDispatcher(this.jsp)
                        .include(context.getRequest(), context.getResponse());
            } catch (Exception ex) {
                context.getOutputWriter().write(ex.getMessage());
                ex.printStackTrace();
            }

        } else {
            // PageHandler old=context.getPageHandler();
            // context.setPageHandler(pageRef.getPageHandler());
            pageRef.getPageHandler().defaultAction(context);

            pageRef.defalutRenderBehavior(context);

        }
    }

    /**
     * renderHeader
     *
     * @param context RenderContext
     * @param sb StringBuffer
     * @param m Map
     * @todo Implement this com.mapbased.wfw.Component method
     */
    public void renderHeader(RenderContext context,StringBuffer sb,Map m)
    {
        if(this.pageRef != null)
        {
            Component[] headables=this.pageRef.getHeadables();
            for(int i=0;i < headables.length;i++)
            {
                headables[i].renderHeader(context,sb,m);
            }
        }
    }

    public boolean isHeadable()
    {
        return this.pageRef != null && this.pageRef.getHeadables().length > 0;
    }

}
